import { isEmptyArr, isNullOrEmpty } from '../is';
import { handleConditionExtend } from '../conditionFormat/useConditionFormat.js';
/**
 * 格式化地图类数据
 * @des {
 *   仅格式化组件所series数据，不处理属性的值
 * }
 */

// 基础地图
export function mapBasicFormat(dataSets) {
  const { source, dimensions, fieldNameChainMap, conditionData, conditionOptions } = dataSets;
  let seriesData = [];
  if (isEmptyArr(source)) {
    return seriesData;
  }
  // 生成数据
  const mapData = source.map((item) => {
    // 存储维度和度量值，以原始字段名称区分
    if (fieldNameChainMap.xAxis && fieldNameChainMap.xAxis[dimensions.xAxis]) {
      conditionData[fieldNameChainMap.xAxis[dimensions.xAxis]].push({
        value: item[dimensions.xAxis],
      });
    }
    if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[dimensions.yAxis]) {
      conditionData[fieldNameChainMap.yAxis[dimensions.yAxis]].push({
        value: item[dimensions.yAxis],
      });
    }
    return {
      value: item[dimensions.yAxis] ? Number(item[dimensions.yAxis]) : 0,
      name: item[dimensions.xAxis],
    };
  });
  seriesData = [{
    name: dimensions.yAxis,
    data: mapData,
    dataFormatType: 'yAxis'
  }];
  // 条件格式处理
  const options = {
    conditionData,
    isExistLegend: false, // 是否存在颜色维度
    seriesData,
    legendFieldName: null,
    fieldNameChainMap,
  };
  handleConditionExtend(options, conditionOptions);
  return seriesData;
}
/**
 * 气泡地图数据转化
 */
export function mapScatterFormat(dataSets) {
  const {
    source,
    dimensions,
    geographyTypes,
    fieldNameChainMap,
    conditionData,
    conditionOptions,
    mapChartJson,
  } = dataSets;
  const { yAxis, xAxis, yAxisAreaColor, yAxisColor } = dimensions;
  let xAxisArr = [];
  let yAxisArr = [];
  let yAxisAreaColorArr = [];
  let yAxisColorArr = [];
  let seriesData = [];
  // 当维度是经度和维度时，将xAxis数组按照经度、维度的顺序放到newXAxis中
  const newXAxis = [];
  const geographyTypesOrder = ['LONGITUDE', 'LATITUDE'];
  if (isEmptyArr(source)) {
    return { seriesData, max: 100};
  }
  const yAreaData = {
    // "地图颜色/度量"的值
    data: [],
    dataFormatType: 'yAxisAreaColor',
    fieldName:
      [fieldNameChainMap.yAxisAreaColor && fieldNameChainMap.yAxisAreaColor[yAxisAreaColor]] || [],
  };
  //地图颜色/度量value
  const yAreaList =[];
  const yData = {
    // "气泡大小/度量"和"气泡颜色/度量"的值
    data: [],
    dataFormatType: 'yAxis',
    fieldName: [],
  };
  // 判断是否是多维度
  if (xAxis && xAxis.includes('&')) {
    xAxisArr = xAxis.split('&');
  } else {
    xAxisArr = isNullOrEmpty(xAxis) ? [] : [xAxis];
  }
  // 判断是否是多度量
  if (yAxis.includes('&')) {
    yAxisArr = yAxis.split('&');
  } else {
    yAxisArr = isNullOrEmpty(yAxis) ? [] : [yAxis];
  }
  if (yAxisAreaColor.includes('&')) {
    yAxisAreaColorArr = yAxisAreaColor.split('&');
  } else {
    yAxisAreaColorArr = isNullOrEmpty(yAxisAreaColor) ? [] : [yAxisAreaColor];
  }
  if (yAxisColor && yAxisColor.includes('&')) {
    yAxisColorArr = yAxisColor.split('&');
  } else {
    yAxisColorArr = isNullOrEmpty(yAxisColor) ? [] : [yAxisColor];
  }
  // 存储度量值原始字段名称
  yData.fieldName = [...yAxisArr, ...yAxisColorArr].map((item) => {
    if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[item]) {
      return fieldNameChainMap.yAxis[item];
    }
    if (fieldNameChainMap.yAxisColor && fieldNameChainMap.yAxisColor[item]) {
      return fieldNameChainMap.yAxisColor[item];
    }
  });
  // 将xAxis数组按照经度、维度的顺序放到newXAxis中
  const { xAxis: xAxisGeographyTypes } = geographyTypes;
  if (xAxisGeographyTypes.includes('&')) {
    const geographyTypeArr = xAxisGeographyTypes.split('&');
    geographyTypesOrder.forEach((item) => {
      geographyTypeArr.forEach((list) => {
        const [name, type] = list.split('.');
        if (item === type) {
          newXAxis.push(name);
        }
      });
    });
  }
  const newYAxisData = Array.from(new Set([...yAxisArr, ...yAxisColorArr])); // 气泡大小度量和气泡颜色度量名称数据去重
  // 生成气泡地图数据
  handleScatterGeoData({
    source,
    xAxisArr,
    yAxisArr,
    yAxisData: newYAxisData,
    yData: yData.data,
    newXAxis,
    yAxisAreaColorArr,
    yAreaData: yAreaData.data,
    fieldNameChainMap,
    conditionData,
    conditionOptions,
    yFieldName: yData.fieldName,
    yAreaFieldName: yAreaData.fieldName,
    mapChartJson,
    yAreaList,
  });
  const ySeries = { ...yData };
  const yAreaColorSeries = { ...yAreaData };
  seriesData = [ySeries, yAreaColorSeries];
  const max = isEmptyArr(yAreaList) ? 100 : Math.max(...yAreaList);
  return { seriesData, max };
}
// 处理气泡地图数据
function handleScatterGeoData({
  source,
  xAxisArr,
  yAxisArr,
  yAxisData,
  yData,
  newXAxis,
  yAxisAreaColorArr,
  yAreaData,
  fieldNameChainMap,
  conditionData,
  conditionOptions,
  yFieldName,
  yAreaFieldName,
  mapChartJson,
  yAreaList,
}) {
  // 是否设置了“地区颜色/度量”，目前地图颜色不支持维度是经纬度的情况, xAxis.length === 1 && newXAxis.length === 0表示维度是地区名
  const yAxisAreaColorExist =
    !isEmptyArr(yAxisAreaColorArr) && xAxisArr.length === 1 && newXAxis.length === 0;
  source.forEach((dataItem, index) => {
    const tooltip = {};
    yAxisArr.forEach((item,index)=>{
        tooltip[item] = dataItem[item] || '';
    });
    /*
     * 气泡图维度分:
     * 1.出发地区和目的地区都是地区的
     * 2.出发地区和目的地址都是经纬度(Todo)
     */
    // 维度信息为地区 维度只有一条并且不是经纬度类型的，数据存在
    if (xAxisArr.length === 1 && newXAxis.length === 0 && !isEmptyArr(yAxisData)) {
      const geoData = mapChartJson?.features?.find((item) => {
        return item.properties.name === dataItem[xAxisArr[0]];
      });
      if (geoData  && geoData.properties.center) {
        yData.push({
          value: [...geoData.properties.center, dataItem[yAxisData[0]] ? Number(dataItem[yAxisData[0]]) : 0],
          tooltip: tooltip,
          name: geoData.properties.name,
          dataFormatType: 'yAxis'
        });
        // 维度只有一个时，存储维度值，以原始字段名称区分
        if (fieldNameChainMap.xAxis && fieldNameChainMap.xAxis[xAxisArr[0]]) {
          conditionData[fieldNameChainMap.xAxis[xAxisArr[0]]].push({
            value: dataItem[xAxisArr[0]],
          });
        }
        // 存储度量值，以原始字段名称区分
        yAxisData.map((list) => {
          if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[list]) {
            conditionData[fieldNameChainMap.yAxis[list]].push({
              value: dataItem[list],
            });
          }
          // 气泡地图的气泡大小和气泡颜色拖拽的度量有可能是同一个数据,需排除
          if (
            fieldNameChainMap.yAxisColor &&
            fieldNameChainMap.yAxisColor[list] &&
            fieldNameChainMap.yAxisColor[list] !== fieldNameChainMap.yAxis[list]
          ) {
            conditionData[fieldNameChainMap.yAxisColor[list]].push({
              value: dataItem[list],
            });
          }
        });
      }
    }
    // 维度信息为经纬度
    if (newXAxis.length === 2 && !isEmptyArr(yAxisData)) {
      const value = [...newXAxis, yAxisData[0]].map((item) => {
        const itemValue = dataItem[item] !== null ? dataItem[item] : 0;
        // 存储维度和度量值，以原始字段名称区分
        if (fieldNameChainMap.xAxis && fieldNameChainMap.xAxis[item]) {
          conditionData[fieldNameChainMap.xAxis[item]].push({
            value: itemValue ? Number(itemValue) : 0,
          });
        }
        if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[item]) {
          conditionData[fieldNameChainMap.yAxis[item]].push({
            value: itemValue ? Number(itemValue) : 0,
          });
        }
        // 气泡地图的气泡大小和气泡颜色拖拽的度量有可能是同一个数据,需排除
        if (
          fieldNameChainMap.yAxisColor &&
          fieldNameChainMap.yAxisColor[item] &&
          fieldNameChainMap.yAxisColor[item] !== fieldNameChainMap.yAxis[item]
        ) {
          conditionData[fieldNameChainMap.yAxisColor[item]].push({
            value: itemValue ? Number(itemValue) : 0,
          });
        }
        return itemValue;
      });
      yData.push({ name: '', value, tooltip: tooltip, dataFormatType: 'yAxis' });
    }
    // 生成底图地图数据
    if (yAxisAreaColorExist) {
      const value = dataItem[yAxisAreaColorArr[0]] ? Number(dataItem[yAxisAreaColorArr[0]]) : 0
      yAreaData.push({
        value,
        name: dataItem[xAxisArr[0]],
        dataFormatType: 'yAxisAreaColor'
      });
      yAreaList.push(value);
      // 存储度量值，以原始字段名称区分，地图数据的值有可能和气泡数据使用同一个度量值，避免数据存储重复，!yAxisData.includes(yAxisAreaColorArr[0])
      if (
        fieldNameChainMap.yAxisAreaColor &&
        fieldNameChainMap.yAxisAreaColor[yAxisAreaColorArr[0]] &&
        !yAxisData.includes(yAxisAreaColorArr[0])
      ) {
        conditionData[fieldNameChainMap.yAxisAreaColor[yAxisAreaColorArr[0]]].push({
          value: dataItem[yAxisAreaColorArr[0]],
        });
      }
    }
  });
  // 条件格式处理
  const options = {
    conditionData,
    isExistLegend: false, // 是否存在颜色维度
    seriesData: [
      {
        data: yData,
        fieldName: yFieldName,
      },
      {
        data: yAreaData,
        fieldName: yAreaFieldName,
      },
    ],
    legendFieldName: null,
    fieldNameChainMap,
    chartTag: 'scatterMap',
  };
  handleConditionExtend(options, conditionOptions);
}

/**
 * 飞线地图数据转化
 */
export function mapFlyingLinesFormat(dataSets) {
  const {
    source,
    dimensions,
    geographyTypes,
    fieldNameChainMap,
    conditionData,
    conditionOptions,
    mapChartJson,
  } = dataSets;
  if (isEmptyArr(source)) {
    return {
      series: [
        {
          name: '',
          data: [],
        },
        {
          name: '',
          data: [],
        },
      ],
    };
  }
  const { yAxis, xAxis, xAxisArea, xAxisMap, yAxisAreaColor } = dimensions;
  // 当维度是经度和维度时，将xAxis数组按照经度、维度的顺序放到newXAxis中
  const newXAxis = [];
  const newXAxisMap = [];
  const geographyTypesOrder = ['LONGITUDE', 'LATITUDE'];
  let xAxisArr = [];
  let xAxisAreaArr = [];
  let yAxisArr = [];
  let xAxisMapArr = [];
  let yAxisAreaColorArr = [];
  const lineList = []; // 飞线数据
  const yData = []; // 散点数据
  // 存储出发地名称数据和原始字段名称
  const xAxisData = {
    data: [],
  };
  const yAreaData = {
    // "地图颜色/度量"的值
    data: [],
    dataFormatType: 'yAxisAreaColor',
    fieldName:
      [fieldNameChainMap.yAxisAreaColor && fieldNameChainMap.yAxisAreaColor[yAxisAreaColor]] || [],
  };
  // 存储目的地名称数据和原始字段名称
  const xAxisMapData = {
    data: [],
  };
  // 判断是否是多维度
  if (xAxis.includes('&')) {
    xAxisArr = xAxis.split('&');
  } else {
    xAxisArr = [xAxis];
  }
  if (xAxisArea.includes('&')) {
    xAxisAreaArr = xAxisArea.split('&');
  } else {
    xAxisAreaArr = [xAxisArea];
  }
  if (xAxisMap.includes('&')) {
    xAxisMapArr = xAxisMap.split('&');
  } else {
    xAxisMapArr = [xAxisMap];
  }
  if (yAxisAreaColor.includes('&')) {
    yAxisAreaColorArr = yAxisAreaColor.split('&');
  } else {
    yAxisAreaColorArr = isNullOrEmpty(yAxisAreaColor) ? [] : [yAxisAreaColor];
  }
  // 判断是否是多度量
  if (yAxis.includes('&')) {
    yAxisArr = yAxis.split('&');
  } else {
    yAxisArr = [yAxis];
  }
  if (!yAxis) {
    return {};
  }
  // 将xAxis和xAxisMap数组按照经度、维度的顺序放到newXAxis和newXAxisMap中
  const { xAxis: xAxisGeographyTypes, xAxisMap: xAxisMapGeographyTypes } = geographyTypes;
  if (xAxisGeographyTypes.includes('&')) {
    const geographyTypeArr = xAxisGeographyTypes.split('&');
    geographyTypesOrder.forEach((item) => {
      geographyTypeArr.forEach((list) => {
        const [name, type] = list.split('.');
        if (item === type) {
          newXAxis.push(name);
        }
      });
    });
  }
  if (xAxisMapGeographyTypes.includes('&')) {
    const geographyTypeArr = xAxisMapGeographyTypes.split('&');
    geographyTypesOrder.forEach((item) => {
      geographyTypeArr.forEach((list) => {
        const [name, type] = list.split('.');
        if (item === type) {
          newXAxisMap.push(name);
        }
      });
    });
  }
  // 生成飞线地图数据
  handleFlyingLinesData({
    source,
    yAxisArr,
    xAxisArr,
    xAxisAreaArr,
    xAxisMapArr,
    yData,
    yAxisData: yAxisAreaColorArr,
    yAxisAreaColorArr,
    yAreaData: yAreaData.data,
    lineList,
    xAxisData,
    xAxisMapData,
    newXAxis,
    newXAxisMap,
    fieldNameChainMap,
    conditionData,
    conditionOptions,
    mapChartJson,
    yAreaFieldName: yAreaData.fieldName,
  });
  const seriesData = [
    {
      data: yData,
    },
    {
      dataFormatType: 'yAxis',
      data: lineList,
    },
    {
      ...yAreaData,
    }
  ];
  return seriesData;
}

// 处理飞线地图数据
async function handleFlyingLinesData({
  source,
  yAxisArr,
  xAxisArr,
  xAxisAreaArr,
  xAxisMapArr,
  yData,
  yAxisData,
  yAxisAreaColorArr,
  yAreaData,
  lineList,
  xAxisData,
  xAxisMapData,
  newXAxis,
  newXAxisMap,
  fieldNameChainMap,
  conditionData,
  conditionOptions,
  mapChartJson,
  yAreaFieldName,
}) {
  // 以防地区名称重复，记录已存在的地区名称
  const cityNamelist = []; // 记录地区名称
   // 是否设置了“地区颜色/度量”，目前地图颜色不支持维度是经纬度的情况, xAxis.length === 1 && newXAxis.length === 0表示维度是地区名
  const yAxisAreaColorExist =
  !isEmptyArr(yAxisAreaColorArr) && xAxisArr.length === 1 && newXAxis.length === 0;
  source.forEach((dataItem) => {
    // 获取度量值
    const linesValue = yAxisArr.map((yItem) => {
      // 存储度量值，以原始字段名称存储
      if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[yItem]) {
        conditionData[fieldNameChainMap.yAxis[yItem]].push({
          value: dataItem[yItem],
        });
      }
      return {
        name: yItem,
        value: dataItem[yItem],
      };
    });
    // 出发地和目的地经纬度数据
    const geoData = {
      fromName: '', // 出发地点
      toName: '', // 目的地点
      fromCoord: '', // 出发地经纬度
      toCoord: '', // 目的地经纬度
    };
    /*
     * 飞线图维度分
     * 1.出发地区和目的地区都是地区的
     * 2.出发地区和目的地址都是经纬度(Todo)
     */
    // 维度信息为地区
    if (
      xAxisArr.length === 1 &&
      xAxisMapArr.length === 1 &&
      newXAxis.length === 0 &&
      newXAxisMap.length === 0
    ) {
      // 转换数据
      handleFlyingLinesGeoData({
        xAxisName: dataItem[xAxisArr[0]],
        xAxisMapName: dataItem[xAxisMapArr[0]],
        mapChartJson,
        yData,
        geoData,
        cityNamelist,
        xAxisData,
        xAxisMapData,
      });
      if (geoData.fromName && geoData.toName && geoData.fromCoord && geoData.toCoord) {
        lineList.push({
          fromName: geoData.fromName,
          toName: geoData.toName,
          coords: [geoData.fromCoord, geoData.toCoord],
          linesValue,
        });
        // 存储维度值，以原始字段名称存储（维度值为地区名称时）
        if (fieldNameChainMap.xAxis && fieldNameChainMap.xAxis[xAxisArr[0]]) {
          conditionData[fieldNameChainMap.xAxis[xAxisArr[0]]].push({
            value: dataItem[xAxisArr[0]],
          });
        }
        // 起始维度可拖入同一个，以防数据重复存储，开始维度名称不能与结束维度名称一样
        if (
          fieldNameChainMap.xAxisMap &&
          fieldNameChainMap.xAxisMap[xAxisMapArr[0]] &&
          !xAxisArr.includes(xAxisMapArr[0])
        ) {
          conditionData[fieldNameChainMap.xAxisMap[xAxisMapArr[0]]].push({
            value: dataItem[xAxisMapArr[0]],
          });
        }
      }
    }
    // 维度信息为经纬度
    if (newXAxis.length === 2 && newXAxisMap.length === 2) {
      const coords = [newXAxis, newXAxisMap].map((item) => [dataItem[item[0]], dataItem[item[1]]]);
      lineList.push({
        fromName: '',
        toName: '',
        coords,
        linesValue,
      });
      // 出发地经纬度
      const startValue = [...newXAxis].map((item) => dataItem[item]);
      // 目的地经纬度
      const endValue = [...newXAxisMap].map((item) => dataItem[item]);
      yData.push({ name: '', value: startValue });
      yData.push({ name: '', value: endValue });
      // 存储维度值，以原始字段名称存储（维度值为经纬度时）
      [...newXAxis, ...newXAxisMap].map((item) => {
        if (fieldNameChainMap.xAxis && fieldNameChainMap.xAxis[item]) {
          conditionData[fieldNameChainMap.xAxis[item]].push({
            value: dataItem[item],
          });
        }
        if (fieldNameChainMap.xAxisMap && fieldNameChainMap.xAxisMap[item]) {
          conditionData[fieldNameChainMap.xAxisMap[item]].push({
            value: dataItem[item],
          });
        }

      });
    }
    // 生成底图地图数据
    if (yAxisAreaColorExist) {
      yAreaData.push({
        value: dataItem[yAxisAreaColorArr[0]] ? Number(dataItem[yAxisAreaColorArr[0]]) : 0,
        name: dataItem[xAxisAreaArr[0]],
      });
      // 存储度量值，以原始字段名称区分，地图数据的值有可能和气泡数据使用同一个度量值，避免数据存储重复，!yAxisData.includes(yAxisAreaColorArr[0])
      if (
        fieldNameChainMap.yAxisAreaColor &&
        fieldNameChainMap.yAxisAreaColor[yAxisAreaColorArr[0]] &&
        !yAreaData.includes(yAxisAreaColorArr[0])
      ) {
        conditionData[fieldNameChainMap.yAxisAreaColor[yAxisAreaColorArr[0]]].push({
          value: dataItem[yAxisAreaColorArr[0]],
        });
      }
    }
  });
  const fieldName = yAxisArr.map((item) => {
    if (fieldNameChainMap.yAxis && fieldNameChainMap.yAxis[item]) {
      return fieldNameChainMap.yAxis[item];
    }
  });
  // 条件格式处理
  const options = {
    conditionData,
    isExistLegend: false, // 是否存在颜色维度
    seriesData: [
      {
        data: lineList,
        fieldName,
      },
      {
        data: yAreaData,
        fieldName: yAreaFieldName,
      },
    ],
    legendFieldName: null,
    fieldNameChainMap,
    chartTag: 'scatterMap',
  };
  handleConditionExtend(options, conditionOptions);
}

// 处理飞线地图的经纬度数据
function handleFlyingLinesGeoData({
  xAxisName,
  xAxisMapName,
  mapChartJson,
  yData,
  geoData,
  cityNamelist,
  xAxisData,
  xAxisMapData,
}) {
  const fromGeoData = mapChartJson?.features?.find((item) => {
    return item.properties.name === xAxisName;
  });
  const toGeoData = mapChartJson?.features?.find((item) => {
    return item.properties.name === xAxisMapName;
  });
  if (fromGeoData) {
    geoData.fromName = fromGeoData.properties.name;
    geoData.fromCoord = fromGeoData.properties.center;
    // 以防地区名称重复，记录已存在的地区名称
    if (!cityNamelist.includes(geoData.fromName)) {
      const value = fromGeoData.properties.center;
      yData.push({
        name: fromGeoData.properties.name,
        value,
      });
      xAxisData.data.push({
        value: fromGeoData.properties.name,
      });
      cityNamelist.push(fromGeoData.properties.name);
    }
  } else {
    geoData.fromName = '';
    geoData.fromCoord = '';
  }
  if (toGeoData) {
    geoData.toName = toGeoData.properties.name;
    geoData.toCoord = toGeoData.properties.center;
    if (!cityNamelist.includes(geoData.toName)) {
      const value = toGeoData.properties.center;
      yData.push({
        name: toGeoData.properties.name,
        value,
      });
      xAxisMapData.data.push({
        value: toGeoData.properties.name,
      });
      cityNamelist.push(toGeoData.properties.name);
    }
  } else {
    geoData.toName = '';
    geoData.toCoord = '';
  }
}
